package me.jiatao.wan.ui.main.mine

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.app.ActivityCompat.recreate
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.hi.dhl.binding.databind
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.jiatao.eventbus.observe.observeEvent
import me.jiatao.wan.R
import me.jiatao.wan.common.LocalStorage
import me.jiatao.wan.data.UserEvent
import me.jiatao.wan.databinding.FragmentMineBinding
import me.jiatao.wan.model.UserInfoModel
import timber.log.Timber

class MineFragment : Fragment(R.layout.fragment_mine) {
    private val mBinding by databind<FragmentMineBinding>()
    private val mUserInfoModel by lazy { LocalStorage.loadUser() }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.apply {
            mineHeader.userModel = mUserInfoModel
            mineHeader.logout.setOnClickListener {
                MaterialAlertDialogBuilder(requireContext())
                    .setTitle("提示")
                    .setMessage("是否登出?")
                    .setNegativeButton("确定") { _, _ ->
                        LocalStorage.logout()
                        mUserInfoModel.logout()
                    }
                    .setPositiveButton("取消") { _, _ ->

                    }
                    .show()
            }


            switchMode.setOnClickListener{ _ ->
                if (switchMode.isChecked){
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                }else{
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
                }
               requireActivity().recreate()
            }
        }

        /**
         * 监听登录成功回调
         */
        observeEvent<UserEvent> { userEvent ->
            LocalStorage.saveUserName(userEvent.userName)
            mUserInfoModel.setUserName(userEvent.userName)
        }
    }
}